package com.antis.olsl.data.introduction;

import android.os.Build;
import android.view.View;
import android.view.ViewOutlineProvider;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.android.arouter.launcher.ARouter;
import com.antis.olsl.arouterlib.DataRoutePath;
import com.antis.olsl.base.BaseActivity;
import com.antis.olsl.base.utils.ToastUtil;
import com.antis.olsl.data.R;
import com.antis.olsl.data.adapter.IntroductionSlipListAdapter;
import com.antis.olsl.data.databinding.ActivityIntroductionQueryBinding;
import com.antis.olsl.data.response.GetIntroductionSlipListRes;
import com.antis.olsl.library.bean.IntroductionInfo;
import com.antis.olsl.library.dialog.ChooseDateDialog;
import com.antis.olsl.library.widget.MyInputSearchLayout;
import com.chad.library.adapter.base.listener.OnLoadMoreListener;
import com.trello.rxlifecycle2.LifecycleTransformer;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

/**
 * @ProjectName: ATS_OLSL
 * @Package: com.antis.olsl.activity.purchaseQuery
 * @ClassName: PurchaseQueryActivity
 * @Description: 引进查询
 * @Author: 羊琪
 * @CreateDate: 2020/3/30 19:37
 * @UpdateDate: 2020/3/30 19:37
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
@Route(path = DataRoutePath.ACTIVITY_INTRODUCTION_QUERY)
public class IntroductionQueryActivity extends BaseActivity<ActivityIntroductionQueryBinding> implements View.OnClickListener,
        ChooseDateDialog.ChooseDateListener, IntroductionQueryContract.View, MyInputSearchLayout.TextChangedListener, OnLoadMoreListener {
    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());
    private SimpleDateFormat textDateFormat = new SimpleDateFormat("yyyy年MM月dd日", Locale.getDefault());

    private Date startDate;
    private Date endDate;
    private int pageNum = 1;
    private int maxPage = 1;
    private ChooseDateDialog chooseDateDialog;
    private ArrayList<IntroductionInfo> infos = new ArrayList<>();
    private IntroductionSlipListAdapter adapter;

    private boolean chooseSalesroom = false;
    private String searchText = "";

    private IntroductionQueryPresenter mPresenter;

    @Override
    protected ActivityIntroductionQueryBinding getViewBinding() {
        return ActivityIntroductionQueryBinding.inflate(getLayoutInflater(), baseBinding.getRoot(), true);
    }

    @Override
    protected void initPresenter() {
        super.initPresenter();
        mPresenter = new IntroductionQueryPresenter();
        mPresenter.takeView(this);
    }

    @Override
    protected void initViews() {
        ARouter.getInstance().inject(this);
        setSupportActionBar(viewBinding.toolbar);
        //去掉上滑时顶部阴影
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            viewBinding.appBarLayout.setOutlineProvider(null);
            viewBinding.coordinatorLayout.setOutlineProvider(ViewOutlineProvider.BOUNDS);
        }

        adapter = new IntroductionSlipListAdapter(infos);
        viewBinding.recyclerView.setLayoutManager(new LinearLayoutManager(this));
        viewBinding.recyclerView.setAdapter(adapter);

        viewBinding.layoutSearchInput.myInputSearchLayout.setHintText("请输入供应商名称");
        viewBinding.layoutSearchInput.myInputSearchLayout.setListener(this);
        adapter.getLoadMoreModule().setOnLoadMoreListener(this);
        adapter.setOnItemClickListener((adapter, view, position) -> {
            String purchaseSlipId = infos.get(position).getIntroductionNumber();
            ARouter.getInstance()
                    .build(DataRoutePath.ACTIVITY_INTRODUCTION_SLIP_DETAIL)
                    .withBoolean("type", chooseSalesroom)
                    .withString("purchaseSlipId", purchaseSlipId)
                    .navigation();
        });

        initDate();
        viewBinding.rlChooseDate.setOnClickListener(this);
    }

    @Override
    protected void initData() {
        flushData();
    }

    /**
     * 刷新数据
     */
    private void flushData() {
        HashMap<String, Object> map = new HashMap<>();
        //输入的关键字查询
        map.put("supplierName", searchText);
        map.put("startDate", simpleDateFormat.format(startDate));
        map.put("endDate", simpleDateFormat.format(endDate));
        map.put("pageNum", pageNum);
        map.put("pageSize", 10);
        mPresenter.selectPurchaseIntroduceList(map);
    }

    private void initDate() {
        Calendar calendar = Calendar.getInstance();

        endDate = new Date();
        calendar.setTime(endDate);
        //初始进来查询近7天的数据
        calendar.add(Calendar.DATE, -7);
        startDate = calendar.getTime();
        setDateText();
    }

    private void setDateText() {
        viewBinding.tvDate.setText(textDateFormat.format(startDate) + "-" + textDateFormat.format(endDate));
    }

    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.rl_chooseDate) {
            chooseDateDialog = new ChooseDateDialog(this, "选择开始时间", startDate, this, "startDate");
        }
    }

    @Override
    public void getDateListener(String tag, int year, int quarter, int month, int week, int day) {
        Date tmpDate = new Date();
        try {
            tmpDate = simpleDateFormat.parse(year + "-" + month + "-" + day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        if (tmpDate.getTime() - System.currentTimeMillis() > 0) {
            ToastUtil.showToast(this, "选择时间不能超过当前时间");
            return;
        }

        if ("startDate".equals(tag)) {
            startDate = tmpDate;
            chooseDateDialog.dismiss();
            chooseDateDialog = new ChooseDateDialog(this, "选择结束时间", endDate, this, "endDate");

        } else {
            if (tmpDate.getTime() - startDate.getTime() < 0) {
                ToastUtil.showToast(this, "结束时间必须大于开始时间");
                return;
            }
            endDate = tmpDate;
            chooseDateDialog.dismiss();
            pageNum = 1;
            flushData();
        }
        setDateText();
    }

    @Override
    public void onTextChangeListener(String text) {
        pageNum = 1;
        searchText = text;
        flushData();
    }

    @Override
    public void onLoadMore() {
        if (pageNum == 1) {
            adapter.getLoadMoreModule().setEnableLoadMore(false);
        }
        if (pageNum < maxPage) {
            pageNum++;
            flushData();
        } else {
            adapter.getLoadMoreModule().loadMoreEnd(false);
        }
    }

    @Override
    public void selectPurchaseIntroduceListSuccess(GetIntroductionSlipListRes resp) {
        if (null != resp.getContent()) {
            maxPage = resp.getContent().getTotal() % 10 == 0 ? resp.getContent().getTotal() / 10 : resp.getContent().getTotal() / 10 + 1;
            if (pageNum == 1) {
                infos.clear();
            }
            if (resp.getContent().getObject() != null) {
                infos.addAll(resp.getContent().getObject());
            }
            adapter.setList(resp.getContent().getObject());
        }
        adapter.getLoadMoreModule().setEnableLoadMore(false);
        adapter.getLoadMoreModule().loadMoreComplete();
    }

    @Override
    public void selectPurchaseIntroduceListFailure(String msg) {
        if (pageNum == 1) {
            infos.clear();
            adapter.setList(infos);
        }
        adapter.getLoadMoreModule().loadMoreEnd();
    }

    @Override
    public boolean isActive() {
        return false;
    }

    @Override
    public <T> LifecycleTransformer<T> bindToLife() {
        return bindToLifecycle();
    }
}
